package com.cheer.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cheer.dao.OaUserDao;
import com.cheer.entity.OaUserEntity;
import com.cheer.service.OaIntegralService;
import com.cheer.service.OaUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service("oaUserService")
public class OaUserServiceImpl extends ServiceImpl<OaUserDao, OaUserEntity> implements OaUserService {

    @Autowired
    private OaUserDao oaUserDao;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private OaIntegralService oaIntegralService;

    @Override
    public Integer getIdByOpenid(String openid) {

        String userIdStr = (String) stringRedisTemplate.boundHashOps("openIdMap").get(openid);
        if( StrUtil.isBlank( userIdStr ) ){
            Integer userId = oaUserDao.selectIdByOpenid(openid);
            if( Objects.isNull(userId) ){
                return null;
            }else{
                stringRedisTemplate.opsForHash().put("openIdMap", openid, String.valueOf(userId));
                return userId;
            }
        }else{
            return Integer.valueOf(userIdStr);
        }
    }

    @Override
    public void addCredit(Integer oaUserId, Integer credit) {
        OaUserEntity oaUserEntity = oaUserDao.selectById(oaUserId);
        oaUserEntity.addIntegral(credit);
        oaUserDao.updateById(oaUserEntity);
        oaIntegralService.updateYearCatch(oaUserId, credit);
    }

}